package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.StatusConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {
    private static final Logger log = LoggerFactory.getLogger(RoleServiceImpl.class);
    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    RoleResourceMapper roleResourceMapper;

    /**
     * 角色添加
     *
     * @param roleDto
     */
    @Override
    public void add(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    /**
     * 角色分页
     *
     * @param roleDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResponse<RoleVo> page(RoleDto roleDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        Role role = BeanUtil.toBean(roleDto, Role.class);
        Page<RoleVo> page = roleMapper.select(role);

        PageResponse<RoleVo> pageResponse = new PageResponse<>(page);
        pageResponse.setRecords(page.getResult());
        return pageResponse;
    }

    /**
     * 删除角色
     *
     * @param roleIds
     */
    @Override
    public void deleteById(String roleIds) {
        Long id = Long.valueOf(roleIds);

        // 根据id查询角色
        Role role = roleMapper.selectByPrimaryKey(id);

        if (ObjectUtil.isEmpty(role)) {
            // 角色不存在
            throw new RuntimeException("角色不存在");
        }

        // 判断角色的status是否==0
        if (ObjectUtil.equalsAny(role, StatusConstant.ENABLE)) {
            // 启用状态下不可删除
            throw new BaseException(BasicEnum.STATUS_IS_START_ERROR);
        }

        // 查询角色是否分配用户
        List<UserRole> userRoleList = userRoleMapper.selectCountByRoleId(id);
        if (ObjectUtil.isNotEmpty(userRoleList)) {
            // 该角色已分配用户,不能删除
            throw new BaseException(BasicEnum.ROLE_DISTRIBUTED);
        }

        // 删除角色
        roleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 角色修改
     *
     * @param roleDto
     */
    @Transactional
    @Override
    public boolean update(RoleDto roleDto) {
        // 查询角色是否分配用户
        List<UserRole> userRoleList = userRoleMapper.selectCountByRoleId(roleDto.getId());
        // 角色绑定的用户不为空 且 当前 status为 1 传入的数据为 禁用状态
        if (ObjectUtil.isNotEmpty(userRoleList) && ObjectUtil.equalsAny(roleDto.getDataState(), StatusConstant.DISABLE.toString())) {
            // 角色与用户关联的状态 status = 0 启用状态
            throw new RuntimeException("该角色已分配用户，不能禁用");
        }

        Role role = BeanUtil.toBean(roleDto, Role.class);
        // 往角色表中添加角色
        roleMapper.updateByPrimaryKeySelective(role);

        // 删除旧的角色资源关联表
        roleResourceMapper.batchDeleteByRoleId(roleDto.getId());

        // 往角色资源关联表中批量添加
        List<RoleResource> roleResourceList = Arrays.stream(roleDto.getCheckedResourceNos()).map(checkedResourceNos -> {
            return RoleResource.builder().dataState(StatusConstant.ENABLE.toString()).roleId(roleDto.getId()).resourceNo(checkedResourceNos).build();
        }).collect(Collectors.toList());

        roleResourceMapper.batchInsert(roleResourceList);

        return true;
    }

    /**
     * 根据角色查询选中的资源数据
     * @param roleId
     * @return
     */
    @Override
    public String[] getResourcesNoByRoleId(Long roleId) {
        return roleResourceMapper.getResourcesNoByRoleId(roleId);
    }

    /**
     * 角色下拉框
     * @return
     */
    @Override
    public List<RoleVo> getAll() {
        List<Role> roleList = roleMapper.getAll();
        return BeanUtil.copyToList(roleList,RoleVo.class);
    }
}
